package com.wise.service.portal.content.menus;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wise.entities.content.Menu;
import com.wise.entities.content.MenuState;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoList;
import com.wise.model.content.enums.MenuExtContentType;
import com.wise.model.content.enums.MenuShowStatus;
import com.wise.service.cms.content.menu.UpdateMenuService;
import com.wise.summer.v1.cms.content.products.ListProducts;
import com.wise.summer.v1.portal.content.menus.ListMenus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
@SummerService
@Slf4j
public class ListMenusService implements SummerServiceBean<ListMenus> {
	@Override
	public void sum(ListMenus model) {
		//查询菜单，若有条件查询可加入条件
		List<Menu> allMenu = getAllMenu();
		//父菜单集合
		List<Menu> menuList = getChild(allMenu, it -> StringUtils.isEmpty(it.getParentId()));
		List<ListMenus.Result> results = toResult(menuList);
		model.setSummerResult(results);
	}

	/**
	 * 查询所有菜单
	 *
	 * @return
	 */
	private List<Menu> getAllMenu() {
		SqlSelect selec = SqlSelect.selec("*")
				.fromClassName(Menu.class)
				.eqLang(Menu._lang);
		return DaoList.s(Menu.class, selec);
	}

	/**
	 * 获取子菜单集合
	 *
	 * @param allMenu   所有菜单集合
	 * @param predicate
	 * @return
	 */
	private List<Menu> getChild(List<Menu> allMenu, Predicate<Menu> predicate) {
		List<Menu> childList = allMenu.stream()
				.filter(predicate)
				.filter(it -> MenuState.USED.isValue(it.getState()))
				.sorted(Comparator.comparingInt(Menu::getSeqencing))
				.collect(Collectors.toList());

		/* 递归 */
		for (Menu menu : childList) {
			menu.setChildList(getChild(allMenu, it -> Objects.equals(menu.getId(), it.getParentId())));
		}
		/* 退出递归条件 */
		return CollectionUtils.isEmpty(childList) ? Collections.emptyList() : childList;

	}

	private List<ListMenus.Result> toResult(List<Menu> menuList) {
		if (CollectionUtil.isEmpty(menuList)) {
			return Collections.emptyList();
		}
		return menuList.stream()
				.filter(it -> MenuState.USED.isValue(it.getState()) || MenuShowStatus.SHOW.isValue(it.getShowStatus()))
				.map(it -> {
					ListMenus.Result result = new ListMenus.Result();
					BeanUtil.copyProperties(it, result);
					List<Menu.ExtContent> extContentList = UpdateMenuService.getAndCheckExtContent(it.getType(), it.getExtContent());
					//此方法
					ListProducts.Result productMap = getProductByCategoryId(extContentList);
					if (!Objects.isNull(productMap)) {
						if (CollectionUtil.isNotEmpty(extContentList)) {
							assert extContentList != null;
							List<JSONObject> extJsonList = extContentList.stream().map(ext -> {
										JSONObject extJson = (JSONObject) JSONObject.toJSON(ext);
										if (MenuExtContentType.NEW_PRODUCT.isValue(ext.getType())) {
											extJson.put("new_recommend", productMap.getNewRecommendProducts());
										} else if (MenuExtContentType.PRODUCT.isValue(ext.getType())) {
											JSONArray infosJson = extJson.getJSONArray("info");
											if (CollectionUtil.isNotEmpty(infosJson)) {
												Map<String, List<ListProducts.ProductResult>> productList4Category = productMap.getProductList4Category();
												for (int i = 0; i < infosJson.size(); i++) {
													JSONObject info = infosJson.getJSONObject(i);
													info.put("products", productList4Category.get(info.getString("id")));
												}
											}
										} else {
											JSONArray infosJson = extJson.getJSONArray("info");
											if (CollectionUtil.isNotEmpty(infosJson)) {
												Map<String, List<ListProducts.ProductResult>> productList4Category = productMap.getProductList4Category();
												for (int i = 0; i < infosJson.size(); i++) {
													JSONObject info = infosJson.getJSONObject(i);
													info.put("industry", productList4Category.get(info.getString("id")));
												}
											}
										}
										return extJson;
									}).collect(Collectors.toList());
							result.setExtContent(JSON.toJSONString(extJsonList));
						}
					}
					result.setChildList(toResult(it.getChildList()));
					return result;
				}).collect(Collectors.toList());
	}

	private ListProducts.Result getProductByCategoryId(List<Menu.ExtContent> extContentList) {
		List<Object> categoryIdList = getCategoryListFromExtContent(extContentList);
		if (CollectionUtil.isEmpty(categoryIdList)) {
			if (extContentList != null) {
				if (extContentList.size() == 1) {
					if (MenuExtContentType.NEW_PRODUCT.isValue(extContentList.get(0).getType())) {
						ListProducts listProducts = new ListProducts();
						listProducts.sum();
						return listProducts.getSummerResult();
					}
				}
			}
			return null;
		}
		ListProducts listProducts = new ListProducts();
		listProducts.setCategoryIds(categoryIdList);
		listProducts.sum();
		return listProducts.getSummerResult();
	}

	/**
	 * 获取所有配置的产品分类ID列表
	 *
	 * @param extContentList
	 * @return
	 */
	private List<Object> getCategoryListFromExtContent(List<Menu.ExtContent> extContentList) {
		if (CollectionUtil.isEmpty(extContentList)) {
			return Collections.emptyList();
		}
		List<Object> categoryList = new ArrayList<>(20);
		extContentList.forEach(ext -> {
			if (!MenuExtContentType.PRODUCT.isValue(ext.getType())
					&& !MenuExtContentType.INDUSTRY.isValue(ext.getType())) {
				return;
			}
			if (CollectionUtil.isEmpty(ext.getInfo())) {
				return;
			}
			categoryList.addAll(ext.getInfo()
					.stream()
					.map(Menu.ProductExtContent::getId)
					.collect(Collectors.toList()));
		});
		return categoryList;
	}
}
